<template>
  <div>
    <div id="side-menu" class="blue noselect">
      <div class="logo">
        <div>
          <i class="fa fa-camera-retro"></i> Label
        </div>
        <div style="font-size:23px">zwibbler demo</div>
      </div>
      <div class="tools">
        <a title="Pick tool" id=pick-tool><i class="fa fa-hand-o-up"></i></a>
        <a title="Insert image" id="insert-image"><i class="fa fa-file-image-o"></i></a>
        <a title="Insert text" id="text-tool"><i class="fa fa-font"></i></a><br>
        <a title="Pencil" id="pencil-tool"><i class="fa fa-pencil"></i></a>
        <a title="Square" id="square-tool"><i class="fa fa-square-o"></i></a>
        <a title="Circle" id="line-tool"><i class="fa fa-long-arrow-right"></i></a><br>
        <!--<a title="Circle" id="erase-tool"><i class="fa fa-eraser"></i></a>-->
      </div>
      <div class="tools-small" style="margin-top:20px">
        <a title="Cut" href="javascript:undefined" id="cut"><i class="fa fa-cut"></i></a>
        <a title="Copy" href="javascript:undefined" id="copy"><i class="fa fa-copy"></i></a>
        <a title="Paste" href="javascript:undefined" id="paste"><i class="fa fa-paste"></i></a>
        <a title="undo" href="javascript:undefined" id="undo"><i class="fa fa-undo"></i></a>
        <a title="redo" href="javascript:undefined" id="redo"><i class="fa fa-repeat"></i></a>
      </div>

      <div class="doc-buttons" style="margin-top:20px">
        <!--todo: change pop up -->
        <a title="New" id="new-document"><i class="fa fa-file-o"></i> New</a>
        <!--todo: how to save-->
        <a title="Save" id="save-document"><i class="fa fa-save"></i> Save</a> <br/>
        <a title="Download" id="download-document" style="width: auto"><i class="fa fa-download"></i> Load Last</a>
      </div>

      <div style="margin-top:20px" class="text-tools">
        <!--todo: change size-->
        <a title="Zoom" href="javascript:undefined" id="zoom">
          <i class="fa fa-search"></i>  Zoom</a>

        <a title="Shadow" href="javascript:undefined" id="shadow">
          <i class="fa fa-glass" style="text-shadow: 3px 3px 3px #fff"></i>Add shadow</a>

        <a title="Make transparent" href="javascript:undefined" id="transparent">
          <i class="fa fa-glass" style="opacity:0.5"></i>  Make transparent</a>

        <!--todo: font-->
        <a title="Font" href="javascript:undefined" id=font>
          <i class="fa fa-font"></i>  Change font</a>

        <a title="Inrease font size" href="javascript:undefined" id="font-increase">
          <i class="fa fa-angle-up"></i>  Increase font size</a>

        <a title="Decrease font size" href="javascript:undefined" id="font-decrease">
          <i class="fa fa-angle-down"></i>  Decrease font size</a>

        <a title="Text alignment" href="javascript:undefined" id="alignment">
          <i class="fa fa-align-center"></i>  Text alignment</a>

      </div>

      <form style="display:none" method="post"
            enctype="multipart/form-data"
            action="http://zwibbler.com/temp.py">
            <input type="file" name="file" id="fileinput" accept="image/*">
      </form>

    </div>

    <div id="zwibbler"></div>
    <div id="progress"></div>

    <div id="pages" class="blue noselect">
      <div class="page-buttons">
        <a title="add-page" href="javascript:undefined" id="add-page"><i class="fa fa-plus"></i></a>
        <a title="delete-page" href="javascript:undefined" id="delete-page"><i class="fa fa-minus"></i></a>
      </div>
      <div id="inner-pages"></div>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        zwibbler: null
      }
    },
    mounted () {
      this.initCanvas()
    },
    methods: {
      initCanvas () {
        this.zwibbler = Zwibbler.create("zwibbler", {
          autoPickTool: true,
          showToolbar: false,
          defaultPaperSize: "letter",
          pageView: true,
          pageSelectorDiv: "#inner-pages",
          defaultFontSize: 36,
          defaultFont: "Bitter",
          multilineText: true,
          defaultFillStyle: "transparent",
          sloppy: false,
          //defaultLineWidth: 0,
          //background: "grid",
          //showToolbar: true,        //是否显示工具栏，默认为true
          //showColourPanel: false,   //是否显示颜色画板，默认为false
          //defaultFontSize: 22,      //文本字体大小
          //multilineText: true,      //文本工具是否允许设置换行
          //scrollbars: false,        //是否显示滚动条
          //showPickTool: true,       //是否在内置工具栏中显示选择工具(箭头选择工具)
          //allowTextInShape: false,  //禁止用户在封闭形状内写入字
          //autoPickTool: false,      //绘制形状后，是否允许用户绘制相同类型的形状。
          //defaultStrokeStyle: 'blue',//图形的边框颜色
          //defaultStrokeStyle: "#ff0000",//默认为#000000（默认图形颜色）
          //defaultBrushColour: "#ff0000",//默认为#000000（默认刷子颜色）
          //defaultBrushWidth:2,      //画笔的宽度
          //defaultArrowSize:15,      //控制箭头工具中箭头的大小
          //defaultArrowStyle: 'solid',//箭头样式  simple solid
          //defaultLineWidth: 3,      //图形的边框宽度
          //defaultTextFillStyle:'red',//文本的颜色
          //backgroundImage: "http://localhost:64435/Content/img/top_bg.jpg",
          //defaultZoom: "width",     //缩放背景适应整个画板（测试没反应） width  page
        });

        this.initDOM();

        let zwibbler = this.zwibbler;

        let Zoom = "page";
        zwibbler.setZoom(Zoom);

        $("#zoom").click(function(e) {
          Zoom = Zoom === "page" ? "width" : "page";
          zwibbler.setZoom(Zoom);
        });

        // This function must then insert the image into the document.
        // ---------------------------------------------------------------
        // todo: 上传图片
        $("#fileinput").on("change", function(e) {
          let form = this.parentNode;
          upload(form);
          form.reset();
        });

        function uploadDone(status, result) {
          if (status === "ok") {
            // *******************************************************
            // *******************************************************
            // *******************************************************
            // CHANGE THIS CODE TO PROCESS YOUR OWN RESPONSE
            // *******************************************************
            // *******************************************************
            // *******************************************************
            let url = "http://zwibbler.com/temp.py?fileid=" +
              result.fileid;

            zwibbler.beginTransaction();
            let nodeId = zwibbler.createNode("ImageNode", {
              url: url
            });
            zwibbler.translateNode(nodeId, 100, 100);
            zwibbler.commitTransaction();
          }
        }

        function upload( form ) {
          let progress = new ProgressNotification("Reading file");
          let xhr = new XMLHttpRequest();
          let fd = new FormData(form);

          xhr.upload.addEventListener("progress",
            function( e ) {
              progress.update( e.loaded / e.total );
            }, false
          );

          xhr.addEventListener("load",
            function( e ) {
              progress.done();
              uploadDone( "ok", $.parseJSON( xhr.response ));
            }, false
          );

          xhr.addEventListener("error",
            function( e ) {
              progress.error("Error");
              uploadDone( "error", null);
            }, false
          );

          xhr.addEventListener("abort",
            function( e ) {
              progress.error("Aborted");
              uploadDone( "aborted", null);
            }, false
          );
          xhr.open(form.method, form.action);
          xhr.send(fd);
        }

        // Display multiple upload progress notifications
        function ProgressNotification(name) {
          this.name = name;
          ProgressNotification.all.push(this);
          this.div = $("<div>");
          $("#progress").append(this.div).show();
          this.update(0);
        }

        ProgressNotification.all = [];
        ProgressNotification.prototype = {
          update: function(percent) {
            this.div.text(this.name + "... " + Math.round(percent * 100) +
              "%");
          },

          error: function(message) {
            let self = this;
            let input = $("<input>").
            attr("type", "button").
            val("OK");

            input.click(function(e) {
              self.done();
            });

            this.div.html(this.name + "... " +  message);
            this.div.append(input);
          },

          done: function() {
            this.div.remove();
            let all = ProgressNotification.all;
            for(let i = 0; i < all.length; i++) {
              if (all[i] === this) {
                all.splice(i, 1);
                break;
              }
            }

            if (all.length === 0) {
              $("#progress").hide();
            }
          }
        };

        // ----------------------------------------------------------------
        function SaveDocument() {
          //console.log(zwibbler)
          $.ajax({
            url: "http://zwibbler.com/temp.py",
            type: "POST",
            data: {file: zwibbler.save()},

            success: function(response, status, xhr) {
              $("#working").hide();
              location.hash = "fileid=" + response.fileid;
            },

            error: function(response, status, xhr) {
              $("#working").hide();
              alert("Error: " + status);
            }
          });
          $("#working").show();
        }

        let saveObject = null;
        $("#save-document").click(function(e) {
          //SaveDocument();
          //zwibbler.setConfig("background", "grid")
          saveObject = zwibbler.save("zwibbler3");
        });

        $("#download-document").click(function(e) {
          //zwibbler.download("png", "hhh.png");
          //console.log(saveObject)
          zwibbler.load("zwibbler3", saveObject);
        });

        $("#new-document").click(function(e) {
//          if (!zwibbler.dirty() || confirm("丢弃所有修改?")) {
//            zwibbler.newDocument();
//            location.hash = "";
//          }
          this.$confirm(`确定丢弃所有修改 ？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            zwibbler.newDocument();
            location.hash = "";
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.curGroup = null
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        }.bind(this));

        // ---------------------------------------------------------------
        function OpenDocument(fileid) {
          $.ajax({
            url: "http://zwibbler.com/temp.py",
            type: "GET",
            data: { fileid: fileid },

            success: function(response, status, xhr) {
              $("#working").hide();
              zwibbler.load(response);
            },

            error: function(response, status, xhr) {
              $("#working").hide();
              alert("Error: " + status);
            }
          });
          $("#working").show();
        }

        function SplitQueryString(string, separator) {
          let a, field, fields, i, index, key, value, _i, _len;
          separator = separator || "?";
          a = {};
          index = string.indexOf(separator);
          if (index >= 0) {
            string = string.substr(index + 1);
          }
          index = string.indexOf('#');
          if (index >= 0) {
            string = string.substr(0, index);
          }
          fields = string.split("&");
          for (_i = 0, _len = fields.length; _i < _len; _i++) {
            field = fields[_i];
            i = field.split("=");
            key = decodeURIComponent(i[0]);
            value = i.length > 1 ? decodeURIComponent(i[1]) : "";
            if (key.length) {
              a[key] = value;
            }
          }
          return a;
        }

        let hash = SplitQueryString(location.hash, "#");
        if ("fileid" in hash) {
          OpenDocument(hash["fileid"]);
        }
      },
      initDOM () {
        let zwibbler = this.zwibbler;

        $("#font").hide();
        $("#font-increase").hide();
        $("#font-decrease").hide();
        $("#shadow").hide();
        $("#transparent").hide();
        $("#alignment").hide();

        $("#insert-image").click(function(e) {
          $("#fileinput").click();
        });

        $("#pick-tool").click(function(e) {
          zwibbler.usePickTool();
        });

        $("#text-tool").click(function(e) {
          zwibbler.useTextTool();
        });

        $("#undo").click(function(e) {
          zwibbler.undo();
        });

        $("#redo").click(function(e) {
          zwibbler.redo();
        });

        $("#cut").click(function(e) {
          zwibbler.copy();
          zwibbler.deleteSelection();
        });

        $("#copy").click(function(e) {
          zwibbler.copy();
        });

        $("#paste").click(function(e) {
          zwibbler.paste();
        });

        $("#add-page").click(function(e) {
          zwibbler.setCurrentPage(zwibbler.insertPage(zwibbler.getCurrentPage()+1));
        });

        $("#delete-page").click(function(e) {
          zwibbler.deletePage(zwibbler.getCurrentPage());
        });

        $("#square-tool").click(function(e) {
          //zwibbler.useSquareTool();
          zwibbler.useRectangleTool({
            fillStyle: "transparent"
          });
        });

        $("#line-tool").click(function(e) {
          zwibbler.useLineTool({
            lineWidth: 3
          });
        });

        $("#pencil-tool").click(function(e) {
          zwibbler.useBrushTool();
        });

        $("#erase-tool").click(function(e) {
          zwibbler.useBrushTool("erase", 20);
        });

        let Fonts = [
          "Special Elite",
          "Bitter",
          "Love Ya Like A Sister"
        ];
        let Properties = {};

        // When the selection changes, zwibbler will call this function
        zwibbler.on("selected-nodes", function(e) {
          let ids = zwibbler.getSelectedNodes();

          let types = {};
          Properties = {
            "shadow": false,
            "font": "Bitter",
            "fillStyle": "#808080",
            "textAlign": "left",
            "fontSize": 20
          };

          for(let i = 0; i < ids.length; i++ ) {
            let type = zwibbler.getNodeType(ids[i]);
            if (type === "PathNode") {
              types[type] = true;
              if (zwibbler.getNodeProperty(ids[i], "closed")) {
                type = "PathNode-closed";
              } else {
                type = "PathNode-open";
              }
            } else if (type === "TextNode") {
              Properties["fontName"] = zwibbler.getNodeProperty(ids[i],
                "fontName");
            }

            let shadow = zwibbler.getNodeProperty(ids[i], "shadow");
            if (shadow !== undefined) {
              Properties["shadow"] = shadow;
            }

            let fillStyle = zwibbler.getNodeProperty(ids[i], "fillStyle");
            if (fillStyle !== undefined) {
              Properties["fillStyle"] = fillStyle;
            }

            let alignment = zwibbler.getNodeProperty(ids[i], "textAlign");
            if (alignment !== undefined) {
              Properties["textAlign"] = alignment;
            }

            let fontSize = zwibbler.getNodeProperty(ids[i], "fontSize");
            if (fontSize !== undefined) {
              Properties["fontSize"] = fontSize;
            }

            types[type] = true;
          }

          $("#shadow").toggle(ids.length > 0);
          $("#font").toggle(types["TextNode"] === true);
          $("#transparent").toggle(types["PathNode-closed"] === true);
          $("#alignment").toggle(types["TextNode"] === true);
          $("#font-increase").toggle(types["TextNode"] === true);
          $("#font-decrease").toggle(types["TextNode"] === true);
        });

        $("#shadow").on("click", function(e) {
          Properties["shadow"] = !Properties["shadow"];
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "shadow",
            Properties["shadow"]);
        });

        $("#font").on("click", function(e) {
          let i = 0;
          for(; i < Fonts.length; i++ ) {
            if ( Properties["fontName"] === Fonts[i] ) {
              i += 1;
              break;
            }
          }

          let newFont = Fonts[i%Fonts.length];
          Properties["fontName"] = newFont;

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "fontName", newFont);
        });

        $("#transparent").on("click", function(e) {
          let colour = Zwibbler.parseColour(Properties["fillStyle"]);
          if (colour.a === 1) {
            colour.a = 0.7;
          } else {
            colour.a = 1;
          }

          Properties["fillStyle"] = Zwibbler.makeColour(colour);

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fillStyle", Properties["fillStyle"]);
        });

        $("#font-increase").click(function(e) {
          Properties["fontSize"] *= 1.1;
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fontSize", Properties["fontSize"]);
        });

        $("#font-decrease").click(function(e) {
          Properties["fontSize"] *= 1/1.1;
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fontSize", Properties["fontSize"]);
        });

        $("#alignment").click(function(e) {
          if (Properties["textAlign"] === "left") {
            Properties["textAlign"] = "centre";
          } else if (Properties["textAlign"] === "centre") {
            Properties["textAlign"] = "right";
          } else {
            Properties["textAlign"] = "left";
          }

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "textAlign",
            Properties["textAlign"]);
        });

      }
    }
  }
</script>

<style>
  body {
    overflow: hidden;
  }

  .blue {
    background: #222;
    color: #ccc;
  }

  #side-menu {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 300px;
    overflow-y: auto;
    text-align: center;
    font-family: Arial;
    color: #ccc;
    font-size: 20px;
  }

  #zwibbler {
    position: absolute;
    top: 0;
    left: 300px;
    bottom: 0;
    right: 200px;
  }

  #pages {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    width: 160px;
    padding: 0 20px;
    overflow-y: scroll;
  }

  .logo {
    font-family: "Special Elite";
    font-size: 40px;
    padding: 20px;
    color: orange;
  }

  .tools a {
    color: #ccc;
    width: 54px;
    height: 54px;
    font-size: 40px;
    line-height: 55px;
    border: 2px solid #ccc;
    display: inline-block;
    text-align: center;
    margin: 5px;
    border-radius: 3px;
  }

  .tools-small a {
    color: white;
    width: 30px;
    height: 30px;
    font-size: 18px;
    line-height: 30px;
    border: 2px solid #ccc;
    display: inline-block;
    text-align: center;
    border-radius: 3px;
  }

  .tools a:hover, .tools-small a:hover, .page-buttons a:hover,
  .text-tools a:hover, .doc-buttons a:hover {
    color: #222;
    background: #ccc;
  }

  #progress {
    display: none;
    position: absolute;
    top: 0;
    right: 200px;
    box-shadow: 3px 3px 3px #444;
    background: #ccc;
    color: black;
    border-bottom-left-radius: 4px;
    font-family: arial, sans;
  }

  #progress div {
    border-top: 1px solid #888;
    padding: 5px;
  }

  .noselect {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  select {
    background: transparent;
    color: #ccc;
    padding: 5px;
    border: 2px solid #ccc;
    font-size: 20px;
  }

  .page-buttons a {
    display: inline-block;
    width: 25px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    font-size: 20px;
    color: #ccc;
  }

  .page-buttons {
    text-align: center;
    padding: 10px 0;
  }

  .text-tools a {
    display: block;
    height: 30px;
    font-size: 20px;
    vertical-align: middle;
    text-align: left;
    color: #ccc;
    padding: 10px 55px;
    width: 90%;
    text-decoration: none;
  }

  .text-tools a .fa {
    line-height: 30px;
    text-align: center;
    font-size: 25px;
  }

  .doc-buttons a {
    display: inline-block;
    border: 2px solid #ccc;
    margin: 5px;
    color: #ccc;
    border-radius: 3px;
    padding: 5px;
    cursor: pointer;
    width: 78px;
  }

</style>
